package com.lrm.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice /*可以拦截所有标有注解Controller的页面*/
public class ControllerExceptionHandler {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {

        //请求URL和异常信息错误打印到网页，可以直接查看错误
        logger.error("Request URL : {}, Exception : {}", request.getRequestURL(),e);

        //传递一个异常类和状态类,让springboot自己处理异常
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
        throw e;
        }

        ModelAndView mv=new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);
        mv.setViewName("error/error");//返回页面
        return  mv;
    }
}
